# -*- coding: utf-8 -*- 
# @Time : 2021/11/5 17:48 
# @Author : Orange
# @File : get_zhibiao_P.py

from P_zong.constant_value import *



def get_pointCodeForBigdata(cim_data, deviceId_1, device_id_list):
    """
    :param cim_data:
    :param deviceId_1: 该企业底下所有一级进线的deviceId
    :return: 对应的deviceID和pointProcessedList
    """
    d_name = {}
    flag_P_is_exist = 0
    for i in range(len(deviceId_1)):
        if deviceId_1[i] in device_id_list:  # 若该设备的P是指标测点，再执行下一步
            data = cim_data['data']['deviceTreeBoList'][i]["deviceTreeTplgyBo"]["pointProcessedList"]
            P = [i['pointCodeForBigdata'] for i in data if i['code'] == "P"]
            """一些企业存在配置问题，可能有些进线未配置P，但实体表有数据，这种情况忽略该企业，退出线程"""
            try:
                d_name[deviceId_1[i]] = {"P": P[0]}
            except:
                flag_P_is_exist = 1 # 存在任一进线未配置P，就退出线程
    #             continue
    #
    # if not d_name:
    #     flag_P_is_exist = 1  # 是否退出线程标志位 #若所有进线（P为指标测点的）都未配置P,该标志位为1
    return d_name, flag_P_is_exist


def get_P_data(deviceId, systemCode, start_time, end_time, d_name, downsample):
    l = []
    for i in deviceId:
        l.append(
            {"calcCode": d_name[i]["P"],  # 总功率
             "deviceId": i,
             "systemCode": systemCode,
             "downsample": downsample
             })
    json = {
        "calcInstenceParams": l,
        "check": False,
        "startTime": start_time,
        "endTime": end_time,
        "timeType": "1minute",
        "userKey": "7b4f251ba5743a1e49639ca715641225_energyoverview-release"
    }
    url = BIGDATA_DOMAIN + '/internal/bigdata/calculation/get_result'
    r = requests.post(url, json=json)
    return r.json()


def P_data_process(deviceId, systemCode, start_time, end_time, d_name, downsample):
    """
    :param deviceId:
    :param systemCode:
    :param start_time:
    :param end_time:
    :param d_name:
    :param downsample:
    :return: 从指标数据中获取功率数据
    """
    try:
        data = get_P_data(deviceId, systemCode, start_time, end_time, d_name, downsample)['data']
    except:
        raise ValueError("缺乏物联数据")
    # my_data, timelist = getMetricValue(deviceId, systemCode, data, my_data, l_day)
    # P = my_data['P']
    # P_DATAFRAME = pd.DataFrame(P, index=timelist, columns=["P"])
    #
    temp_DATAFRAME = pd.DataFrame(data[0]['result'])
    P_DATAFRAME = pd.DataFrame(temp_DATAFRAME["value"].values, index=temp_DATAFRAME['bizTime'], columns=["P"])
    for i in range(1, len(data)):
        temp_DATAFRAME = pd.DataFrame(data[i]['result'])
        P_DATAFRAME = pd.DataFrame(temp_DATAFRAME["value"].values, index=temp_DATAFRAME['bizTime'],
                                   columns=["P"]) + P_DATAFRAME

    if P_DATAFRAME.empty:  # 该企业无有效数据
        raise ValueError("DataFrame为空，该企业无有效数据")
    return P_DATAFRAME




# d_name, flag_P_is_exist = get_pointCodeForBigdata(cim_data, device_id)  # 获取业务树测点名称，不固定的
#             if flag_P_is_exist:
#                 return "未配置P"

